package pers.yurwisher.rubick.gateway.filters;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;

/**
 * 自定义请求过滤器
 *
 * @author yq
 * @date 2021年5月8日 10:02:52
 */
@Slf4j
@Component
public class CustomGateWayRequestFilter extends AbstractGateWayFilter {

    private final ModifyRequestBodyGatewayFilterFactory modifyRequestBodyGatewayFilterFactory;
    private final ModifyRequestBodyGatewayFilterFactory.Config config;

    public CustomGateWayRequestFilter(ModifyRequestBodyGatewayFilterFactory modifyRequestBodyGatewayFilterFactory) {
        this.modifyRequestBodyGatewayFilterFactory = modifyRequestBodyGatewayFilterFactory;
        this.config = this.filterConfig();
    }

    private ModifyRequestBodyGatewayFilterFactory.Config filterConfig() {
        ModifyRequestBodyGatewayFilterFactory.Config config = new ModifyRequestBodyGatewayFilterFactory.Config();
        config.setContentType(MediaType.APPLICATION_JSON_VALUE);
        config.setRewriteFunction(String.class, String.class, (exchange, resp) -> {
            //此处可修改请求参数
            log.info("[{}] requestBody:[{}]", exchange.getRequest().getId(), resp);
            return Mono.just(resp);
        });
        return config;
    }

    @Override
    protected boolean ignoreExpress(ServerWebExchange exchange) {
        return false;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();

        String requestId = serverHttpRequest.getId();
        URI uri = serverHttpRequest.getURI();

        MediaType mediaType = serverHttpRequest.getHeaders().getContentType();

        HttpMethod httpMethod = serverHttpRequest.getMethod();

        //打印请求日志 请求ID IP routeId requestPath requestMethod contentType queryParams
        log.info("[{}] [{}] [{}] [{}] [{}] [{}] [{}]",
                requestId,
                this.getIp(serverHttpRequest),
                this.getGatewayRouteId(exchange),
                this.getPath(uri),
                httpMethod,
                mediaType != null ? mediaType.toString() : "",
                this.getQuery(uri));
        if (HttpMethod.POST == httpMethod) {
            // 表单提交 或 json
            if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(mediaType) || MediaType.APPLICATION_JSON.isCompatibleWith(mediaType)) {
                return modifyRequestBodyGatewayFilterFactory.apply(config).filter(exchange, chain);
            }
        }
        return chain.filter(exchange);
    }

    /**
     * 获取route Id
     *
     * @param exchange
     * @return route id
     */
    private String getGatewayRouteId(ServerWebExchange exchange) {
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        return route != null ? route.getId() : "";
    }


    /**
     * 获取IP
     */
    private String getIp(ServerHttpRequest serverHttpRequest) {
        InetSocketAddress address = serverHttpRequest.getRemoteAddress();
        if (address != null) {
            InetAddress inetAddress = address.getAddress();
            if (inetAddress != null) {
                return inetAddress.getHostAddress();
            }
        }
        return null;
    }

    /**
     * 请求路径 如/nacos
     */
    private String getPath(URI uri) {
        return uri != null ? uri.getPath() : null;
    }

    /**
     * 获取url请求参数 形如 a=1&b=2
     */
    private String getQuery(URI uri) {
        return StrUtil.nullToEmpty(uri != null ? uri.getQuery() : "");
    }


    @Override
    public int getOrder() {
        return -100;
    }
}
